package org.example.votingsystem.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.votingsystem.account.Account;
import org.example.votingsystem.account.Result;
import org.example.votingsystem.dao.AccountDao;
import org.example.votingsystem.util.JWTUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(urlPatterns = "/login", name = "login", loadOnStartup = 1)
public class login extends HttpServlet {
    AccountDao accountDao = new AccountDao();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //        接受前端数据 账号和密码

        String id = req.getParameter("account");
        String password = req.getParameter("password");
        Account account = new Account(id, password);
//        判断账号密码是否数据库存在
        try {
            if(accountDao.checkAccountIdAndPassword(id,password)){
                String token = JWTUtil.getToken(account);
                account = accountDao.findAccountById(id);
                account.setToken(token);
                Result result = new Result(200, "成功", account);
                String str = new ObjectMapper().writeValueAsString(result);
                System.out.println(str);
                resp.getWriter().print(str);
            }else{
                Result result = new Result(401, "没有此账号", account);
                String str = new ObjectMapper().writeValueAsString(result);
                System.out.println(str);
                resp.getWriter().print(str);
            }
        } catch (SQLException e) {
            Result result = new Result(500, "成功", null);
            resp.getWriter().print(result);
        }

    }
}
